package cz.data.common.support.db.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

public class SearchUtil {

    public static QueryWrapper<?> parseWhereSql(List<Condition> conditionList) {
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        if (CollectionUtils.isNotEmpty(conditionList)) {
            for (Condition condition : conditionList) {
                if (StringUtils.isBlank(condition.getQueryType())) {
                    continue;
                }
                switch (condition.getQueryType()) {
                    case "eq":
                        queryWrapper.eq(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "ne":
                        queryWrapper.ne(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "like":
                        queryWrapper.like(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "gt":
                        queryWrapper.gt(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "ge":
                        queryWrapper.ge(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "lt":
                        queryWrapper.lt(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "le":
                        queryWrapper.le(isNotBlank(condition.getValue()), condition.getColumn(), condition.getValue());
                        break;
                    case "between":
                        queryWrapper.between(isNotBlank(condition.getLeftValue()) && isNotBlank(condition.getRightValue()),
                                condition.getColumn(), condition.getLeftValue(), condition.getRightValue());
                        break;
                    default:
                        break;
                }
            }
        }
        return queryWrapper;
    }

    public static boolean isNotBlank(Object value) {
        return Objects.nonNull(value) && StringUtils.isNotBlank(value.toString());
    }
}
